﻿using System;
using System.IO;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Collections;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Loong.Store
{
    [Serializable]
    public class HashTableFileStore : Hashtable, Loong.Store.IObjectStore
    {
        private string filename;

        public HashTableFileStore(string filename)
        {
            this.filename = filename;
            this.Load();
        }

        public HashTableFileStore(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }


        public void Load()
        {
            if (!File.Exists(filename))
                return;

            Stream stream = new FileStream(this.filename, FileMode.Open, FileAccess.Read, FileShare.None);
            if (stream != null)
            {
                try
                {
                    // DeSerialize the Hashtable from stream.
                    IFormatter formatter = new BinaryFormatter();
                    Hashtable appData = (Hashtable)formatter.Deserialize(stream);

                    // Enumerate through the collection and load our base Hashtable.
                    IDictionaryEnumerator enumerator = appData.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        this[enumerator.Key] = enumerator.Value;
                    }
                }
                finally
                {
                    // We are done with it.
                    stream.Close();
                }
            }
        }

        public void Save()
        {
            Stream stream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
            if (stream != null)
            {
                try
                {
                    // Serialize the Hashtable into the IsolatedStorage.
                    IFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(stream, (Hashtable)this);
                }
                finally
                {
                    stream.Close();
                }
            }
        }
    }



}
